/**
 * TinyMCE Word Import Plugin
 */
(function () {
    'use strict';
    var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
    function importWord(editor) {
      if (window.WordPaster && window.WordPaster.getInstance) {
        var wordPaster = window.WordPaster.getInstance();
        if (typeof wordPaster.importWord === 'function') {
          wordPaster.SetEditor(editor);
          wordPaster.importWord();
        } else {
          console.log('Word导入功能未正确初始化');
          // 如果未实现，创建基本的文件选择功能
          var input = document.createElement('input');
          input.type = 'file';
          input.accept = '.docx,.doc';
          input.onchange = function() {
            if (this.files && this.files[0]) {
              var file = this.files[0];
              console.log('选择了Word文件:', file.name);
              
              // 这里需要提供文件处理功能
              // 可以通过API上传文件并获取HTML内容
              var formData = new FormData();
              formData.append('file', file);
              
              fetch('/qep/certificate/template/parse-word', {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
              })
              .then(response => response.json())
              .then(data => {
                if (data.code === 200 && data.data) {
                  editor.insertContent(data.data);
                } else {
                  console.error('解析Word文件失败:', data.msg);
                }
              })
              .catch(error => {
                console.error('上传Word文件出错:', error);
              });
            }
          };
          input.click();
        }
      } else {
        console.log('未找到WordPaster插件');
      }
    }

    var register = function (editor) {
      editor.ui.registry.addButton('wordimport', {
        icon: 'wordimport',
        tooltip: '导入Word文档',
        onAction: function () {
          importWord(editor);
        }
      });
    };

    var Plugin = function () {
      global.add('wordimport', function (editor) {
        register(editor);
        return {};
      });
    };

    Plugin();
}());